<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'mesVisual:visual:visualKkMonthData:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #visualKkMonthDataCList>
        <div style="display: flex" class="mb-2">
          <BasicUpload
            ref="uploadRef"
            v-model:value="record.dataMap"
            :bizKey="record.id"
            :bizType="'mesVisual_image'"
            :uploadType="'all'"
            :loadTime="record.__t"
            maxSize="200"
            :showPreview="false"
            @change="(e) => handleChange(e)"
          />
          <a-button class="ml-2" @click="handlePreview">
            <Icon icon="simple-line-icons:eye" /> {{ t('预览') }}
          </a-button>
        </div>

        <BasicTable
          @register="registerVisualKkMonthDataCTable"
          @row-click="handleVisualKkMonthDataCRowClick"
        >
          <template #picView="{ record }">
            <video 
                v-if="handleflag(record.cpath)"
                style="width: 100%;height: 200px"
                :src="record.cpath ? ctxPath + record.cpath : '/resource/img/noSet.png'"
                :controls="true" 
            ></video>
            <a-image
              v-else
              style="height: 60px"
              :src="record.cpath ? ctxPath + record.cpath : '/resource/img/noSet.png'"
            />
          </template>
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" class="pr-2">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>
          <!-- <a-button
          class="mt-2 mb-2"
          @click="handleVisualKkMonthDataCAdd"
          v-auth="'mesVisual:visual:visualKkMonthData:edit'"
        >
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
        </BasicTable>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsmesVisualVisualVisualKkMonthDataForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { createImgPreview } from '/@/components/Preview/index';
  import {
    VisualKkMonthData,
    visualKkMonthDataSave,
    visualKkMonthDataForm,
    findPicInfo,
  } from '/@/api/mesvisual/visual/visualKkMonthData';
  import { useGlobSetting } from '/@/hooks/setting';
  import { BasicUpload } from '/@/components/Upload';

  const emit = defineEmits(['success', 'register']);
  const uploadRef = ref<any>();

  const { t } = useI18n('mesVisual.visual.visualKkMonthData');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<VisualKkMonthData>({} as VisualKkMonthData);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增车间看板数据展示') : t('编辑车间看板数据展示'),
  }));

  const { ctxPath } = useGlobSetting();

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('标题'),
      field: 'title',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      required: true,
    },
    {
      label: t('车间'),
      field: 'workShop',
      component: 'Select',
      componentProps: {
        dictType: 'srm_work_shop',
      },
      required: true,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 600,
      },
      colProps: { lg: 24, md: 24 },
    },
    // {
    //   label: t('图片上传'),
    //   field: 'dataMap',
    //   component: 'Upload',
    //   componentProps: {
    //     loadTime: computed(() => record.value.__t),
    //     bizKey: computed(() => record.value.id),
    //     bizType: 'mesVisual_image',
    //     uploadType: 'iamge',
    //     maxSize: '200',
    //     showPreview: false,
    //     onChange: (e) => {
    //       console.log(e);
    //       handleChange(e);
    //     },
    //   },
    //   colProps: { lg: 24, md: 24 },
    // },
    {
      label: t('图片列表'),
      field: 'visualKkMonthDataCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'visualKkMonthDataCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 24, md: 24 },
  });

  const [registerVisualKkMonthDataCTable, visualKkMonthDataCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleVisualKkMonthDataCDelete.bind(this, record),
          },
          auth: 'mesVisual:visual:visualKkMonthData:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setVisualKkMonthDataCTableData(_res: Recordable) {
    visualKkMonthDataCTable.setColumns([
      {
        title: t('上移 / 下移'),
        slot: 'sortUp',
        width: 70,
      },
      {
        title: t('缩略图'),
        width: 300,
        align: 'left',
        slot: 'picView',
      },
      {
        title: t('图片名称'),
        dataIndex: 'cname',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('图片路径'),
        dataIndex: 'cpath',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
        ifShow: false,
      },
    ]);
    visualKkMonthDataCTable.setTableData(record.value.visualKkMonthDataCList || []);
  }

  function handleVisualKkMonthDataCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleVisualKkMonthDataCAdd() {
    visualKkMonthDataCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleVisualKkMonthDataCDelete(record: Recordable) {
    uploadRef.value.fileList = [];
    visualKkMonthDataCTable.deleteTableDataRecord(record);
  }

  async function getVisualKkMonthDataCList() {
    let visualKkMonthDataCListValid = true;
    let visualKkMonthDataCList: Recordable[] = [];
    for (const record of visualKkMonthDataCTable.getDataSource()) {
      // if (!(await record.onEdit?.(false, true))) {
      //   visualKkMonthDataCListValid = false;
      // }
      visualKkMonthDataCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of visualKkMonthDataCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      visualKkMonthDataCList.push({
        ...record,
        status: '1',
      });
    }
    if (!visualKkMonthDataCListValid) {
      throw { errorFields: [{ name: ['visualKkMonthDataCList'] }] };
    }
    return visualKkMonthDataCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await visualKkMonthDataForm(data);
    record.value = (res.visualKkMonthData || {}) as VisualKkMonthData;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setVisualKkMonthDataCTableData(res);
    setDrawerProps({ loading: false });
    setDrawerProps({ showOkBtn: record.value.status == '0' ? false : true });
  });

  // 处理图片列表变化
  async function handleChange(fileList) {
    let addIds = fileList.mesVisual_image.split(',');
    if (addIds) {
      addIds.forEach(async (e) => {
        //获取图片名称、路径
        const res = await findPicInfo({ id: e });
        if (res.data) {
          res.data.forEach((item) => {
            visualKkMonthDataCTable.insertTableDataRecord({
              id: e,
              isNewRecord: true,
              editable: true,
              cname: item.fileName,
              cpath: item.fileUrl,
            });
          });
        }
      });
    }
  }


  function handleflag(url) {
    let flag = url.includes(".mp4")
    return flag
  }
  function handlePreview() {
    let imgList = [];
    visualKkMonthDataCTable.getDataSource().forEach((item) => {
      let imgUrl = ctxPath + item.cpath;
      imgList.push(imgUrl);
    });
    createImgPreview({ imageList: imgList });
  }

  // 上移
  function clickUp(record) {
    let arr = visualKkMonthDataCTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === 0) {
      return false;
    }
    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    visualKkMonthDataCTable.setTableData(arr || []);
  }

  // 下移
  function clickDown(record) {
    let arr = visualKkMonthDataCTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    visualKkMonthDataCTable.setTableData(arr || []);
  }

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.visualKkMonthDataCList = await getVisualKkMonthDataCList();
      console.log('submit', params, data, record);
      const res = await visualKkMonthDataSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped>
  /deep/ .ant-image {
    height: 200px;
  }
  /deep/ .ant-image-img {
    height: 100% !important;
  }
</style>
